package net.omnivention.wulumuqi;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jdom.JDOMException;

public class WuluProxyServlet extends javax.servlet.http.HttpServlet {

	private final static Logger logger = Logger.getLogger(WuluProxyServlet.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream out = response.getOutputStream();
		String docURL = request.getParameter("docURL");
		if (docURL == null) {
			out.println("docURL must be specified");
			out.close();
			return;
		}

		try {
			ServletContext servletContext = getServletContext();
			if (docURL.indexOf("http://") == -1) {
				docURL = "file:///" + servletContext.getRealPath(docURL);
			}

			logger.debug("docURL=" + docURL);
			HtmlDocument document = WuluUtil.parseDocument(docURL);
			document.init(request, response, servletContext);

			String manipulatorURLs = request.getParameter("manipulatorURLs");
			if (manipulatorURLs != null) {
				document.applyManipulatorsInQueryString(manipulatorURLs);
			}

			out.println(document.toString());

		} catch (FileNotFoundException ex) {
			out.print(ex.toString());
			logger.warn(ex, ex);
		} catch (IOException ex) {
			out.println(ex.toString());
			logger.error(ex, ex);
		} catch (JDOMException e) {
			out.print(e.toString());
			logger.error(e, e);
		}

		out.flush();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		doGet(request, response);
	}

}